﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.Repositories.Membership;
using System.Web.Mvc;
using Proggy.Web.Cms.ViewModels;
using System.Web.Security;
using Proggy.Web.Cms.Context;
using Proggy.Web.Cms.AppHelpers;

namespace Proggy.Web.Cms.Controllers.BackEnd
{
    /// <summary>
    /// Forms auth controller
    /// </summary>
    public class FormsAuthenticationController : ProggyControllerBase
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="repo"></param>
        public FormsAuthenticationController(IMembershipRepository repo)
        {
            this.MembershipRepository = repo;
        }

        /// <summary>
        /// Membership repo
        /// </summary>
        public IMembershipRepository MembershipRepository { get; set; }

        /// <summary>
        /// Logon for forms authentication
        /// </summary>
        /// <returns></returns>
        public ActionResult Logon(string returnUrl)
        {
            return View();
        }

        /// <summary>
        /// Logon GET
        /// </summary>
        /// <returns></returns>
        [HttpGet, ChildActionOnly]
        public ActionResult LogonChildAction(string returnUrl)
        {

            // get model
            var model = this.MembershipRepository.GetLogonViewModel(returnUrl);

            //
            return View(model);

        }

        /// <summary>
        /// Logon POST
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, ChildActionOnly]
        public ActionResult LogonChildAction(ProggyFormsAuthenticationLogonViewModel model)
        {
            // check model state
            if (ModelState.IsValid)
            {
                // start error
                var errorMsg = string.Empty;

                // try to login
                if (this.MembershipRepository.GetFormsAuthenticationOk(model, true, ref errorMsg))
                {
                    // login
                    FormsAuthentication.SetAuthCookie(model.Username, model.KeepMeLoggedOn);

                    // redirect
                    Response.Redirect(string.IsNullOrEmpty(model.ReturnUrl) ? FrontEndRequestContext.GetRootUrl() : model.ReturnUrl, true);
                    return null;
                }
                else
                {
                    ModelState.AddModelError("", errorMsg);
                }
            }

            // error
            return View(model);
        }

        /// <summary>
        /// Log off
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Logoff()
        {
            // sign out            
            ProggyHttpApplication.RemoveMembershipContext();

            // get redirect url
            var redirectUrl = FrontEndRequestContext.GetRootUrl() + "Proggy";

            // redirect to logon
            return RedirectToAction("Logon", new { returnUrl = redirectUrl });
        }

        /// <summary>
        /// Change password partial - GET
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly, HttpGet]
        public ActionResult ChangePassword()
        {
            // check
            if (!Request.IsAuthenticated || MembershipContext.CurrentAuthenticationMode != System.Web.Configuration.AuthenticationMode.Forms)
            {
                return null;
            }

            // get view model
            var model = this.MembershipRepository.GetChangePasswordViewModel();

            //
            return View(model);
        }

        /// <summary>
        /// Change password partial - POST
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ChildActionOnly, HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            // check
            if (!Request.IsAuthenticated || MembershipContext.CurrentAuthenticationMode != System.Web.Configuration.AuthenticationMode.Forms)
            {
                return null;
            }

            // get username
            var username = User.Identity.Name;

            // start err
            var errorMsg = string.Empty;

            // check model state
            if (ModelState.IsValid)
            {
                // checks
                if (this.MembershipRepository.GetChangePasswordOk(model, username, ref errorMsg))
                {
                    // login
                    FormsAuthentication.SignOut();
                    FormsAuthentication.SetAuthCookie(username, false);

                    // return ok view
                    return View("PasswordChangedOk");
                }
            }

            // add
            ModelState.AddModelError("", errorMsg);

            // errors
            return View(model);
        }

        /// <summary>
        /// Register new member GET
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly, HttpGet]
        public ActionResult Register()
        {
            // get view model
            var model = this.MembershipRepository.GetRegisterViewModel();

            //
            return View(model);
        }

        /// <summary>
        /// Register new member POST
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ChildActionOnly, HttpPost]
        public ActionResult Register(RegisterViewModel model)
        {
            // start error
            var errorMsg = string.Empty;

            //
            if (ModelState.IsValid)
            {
                // get url
                var activationUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("Activate");


                // try to register
                if (this.MembershipRepository.GetRegisterNewMemberOk(model, activationUrl, ref errorMsg))
                {
                    //
                    return View("RegisterOk");
                }
            }

            // add error
            ModelState.AddModelError("", errorMsg);

            // error here
            return View(model);
        }

        /// <summary>
        /// Activate membership
        /// </summary>
        /// <param name="g"></param>
        /// <returns></returns>
        public ActionResult Activate(string g)
        {
            // activate
            this.MembershipRepository.ActivateMembership(g);

            //
            return View();
        }

        /// <summary>
        /// Forgotten details
        /// </summary>
        /// <returns></returns>
        public ActionResult Forgot()
        {
            return View();
        }

        /// <summary>
        /// Forgotten details GET
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ForgotChildAction()
        {
            // get model
            var model = this.MembershipRepository.GetForgotViewModel();

            // 
            return View(model);
        }

        /// <summary>
        /// Forgotten detials POST
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ForgotChildAction(ForgotViewModel model)
        {
            // start error
            var errorMsg = string.Empty;

            //
            if (ModelState.IsValid)
            {
                if (this.MembershipRepository.GetResendDetailsOk(model, ref errorMsg))
                {
                    ViewBag.Email = model.EmailAddress;
                    return View("ForgotOk");
                }
            }

            //
            ModelState.AddModelError("", errorMsg);

            //
            return View(model);
        }
    }
}
